﻿<%@ Page Title="" Language="C#" MasterPageFile="~/master/m.master" %>

<script runat="server">

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="../assets/css/plugins/jsTree/style.min.css" rel="stylesheet" />
    <link href="../assets/css/plugins/iCheck/customsmall.css" rel="stylesheet" />
    <link href="../assets/css/plugins/bootstrap-select/bootstrap-select.min.css" rel="stylesheet" />

    <style>
        .system-box .right-side{width: 100%;}
        .system-box .right-content-box{overflow: hidden;}
        .mainContent { height: 100%;background-color: #ffffff; min-width: 650px; }
        .mainContent .part{height: 100%; display: inline-block; background-color: #ffffff; vertical-align: top; border: 1px solid #dddddd;}
        .mainContent .part .title{border-bottom: 1px solid #dddddd; height: 30px; line-height: 30px; padding-left: 5px;    background-color: #eee;}
        .leftPart { width: calc(100% - 763px);  min-width: 220px;overflow: auto;}
        .rightPart{ width: 400px; overflow: auto;}
        .MessagePart{ width: 355px;overflow: auto;}
        .MessagePart2{ width: 355px;overflow: auto;}

        .rightPart .titleText { height: 30px; line-height: 30px; display: inline-block;  }
        .searchbox{width: 180px; display: inline-block; float: right;}
        .btn-filter-users { -ms-border-radius: 0px; border-radius: 0px; }

        table { table-layout: fixed; }
        td { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        #MessageList tr.check, .table-select tbody tr.check td:first-child { border-left: 4px solid #7acf89; }
        #MessageList tr.check td, .table-select tbody tr.check td { background: #dff0d8; color: #222121; }

        #SettingList tr.check, .table-select tbody tr.check td:first-child { border-left: 4px solid #7acf89; }
        #SettingList tr.check td, .table-select tbody tr.check td { background: #dff0d8; color: #222121; }

        .wxBox { position: absolute; right: 2px; top: 2px; display: inline-block; }
        .wxBox .dropdown-toggle { padding-top: 3px !important; padding-bottom: 3px !important; }
        .wxTitle { display: inline-block; position: relative; top: 2px; }
        .wxSelect { display: inline-block; min-width:310px; }

        .MessagePart .list { height: 50%; overflow-y: auto; }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="main" runat="Server">
    <div class="system-box">
        <div class="right-side">
            <div class="btns-container"></div>
            <div class="right-content-box">
                <%--<div class="header-tips">企业微信用户报表授权</div>--%>
                <div class="mainContent">
                    <div class="wxBox">
                        <div class="wxTitle">企业微信：</div>
                        <div class="wxSelect">
                            <select id="wxWorkSelectList" class="selectpicker" title="选择消息类型" data-style="dropdownColor" data-width="100%">
                            </select>
                        </div>
                    </div>
                    <div class="MessagePart part">
                        <div class="list">
                            <div class="title">
                                <div  class="titleText">
                                    待发送列表
                                </div>
                            </div>
                            <div id="">
                                <table class="footable table table-stripped table-list">
                                    <thead>
                                    <tr>
                                        <th style="width: 35px;"> </th>
                                        <th>消息名称</th>
                                        <th style="width: 120px;">消息接收人</th>
                                    </tr>
                                    </thead>
                                    <tbody id="SettingList"></tbody>
                                </table>
                            </div>
                        </div>
                        <div class="list">
                            <div class="title">
                                <div  class="titleText">
                                    消息列表
                                </div>
                            </div>
                            <div id="">
                                <table class="footable table table-stripped table-list">
                                    <thead>
                                    <tr>
                                        <th style="width: 35px;"> </th>
                                        <th>消息名称</th>
                                        <th style="width: 120px;">消息类型</th>
                                    </tr>
                                    </thead>
                                    <tbody id="MessageList"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="leftPart part">
                        <div class="title">
                            部门用户列表
                        </div>
                        <div id="groupdata"></div>
                    </div>
                    <div class="rightPart part">
                        <div class="title">
                            <div  class="titleText">
                                报表列表
                            </div>
                            <div class="searchbox">
                                <div class="input-group">
                                    <input type="text" class="form-control input-sm filter-users" placeholder="查找报表标题">
                                    <span class="input-group-btn">
                                        <button class="btn btn-primary btn-filter-users btn-sm" type="button">查找</button>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div id="UserList">
                            <table class="footable table table-stripped table-list">
                                <thead>
                                <tr>
                                    <th style="width: 35px;"> </th>
                                    <th style="width: 35px;">Id</th>
                                    <th style="width: 80px;">报表标题</th>
                                    <th style="width: 85px;">报表链接</th>
                                </tr>
                                </thead>
                                <tbody id="pageList"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="footer" runat="Server">
    <script src="../assets/js/plugins/iCheck/icheck.min.js"></script>
    <script src="../assets/js/plugins/iCheck/icheckAll.js"></script>
    <script src="../assets/js/page/rScroll.js"></script>
    <script src="../assets/js/page/pageControl.js"></script>
    <%--<script src="../assets/js/page/tableControl.js"></script>--%>
    <script src="../assets/js/plugins/jsTree/jstree.min.js"></script>
    <script src="../assets/js/plugins/bootstrap-select/bootstrap-select.min.js"></script>
    <script src="../assets/js/plugins/bootstrap-select/i18n/defaults-zh_CN.min.js"></script>

    <script type="text/html" id="tpl-rpt-item">
        {{# for(var i = 0, len = d.length; i < len; i++){ }}
        <tr {{# if(i%2 == 0){ }} class="gradeX footable-even"
            {{# }else{ }} class="gradeX footable-odd" {{# } }}>
            <td><input type="radio"  name="rpt"  class="checkPlan" data-index="{{i}}" /></td>
            <td class="Id">{{d[i].Id}}</td>
            <td class="Title">{{d[i].Title}}</td>
            <td class="Link">{{d[i].Link}}</td>
        </tr>
        {{# } }}
    </script>
    
    <script type="text/html" id="tpl-setting-item">
        {{# for(var i = 0, len = d.length; i < len; i++){ }}
        <tr {{# if(i%2 == 0){ }} class="gradeX footable-even"
            {{# }else{ }} class="gradeX footable-odd" {{# } }}>
            <td class="Id" style="display: none;">{{d[i].Id}}</td>
            <td><input type="radio"  name="setting"  class="checkPlan" data-index="{{i}}" /></td>
            <td class="Name" title="{{d[i].AutoSend_MsgTemplate.Name}}">{{d[i].AutoSend_MsgTemplate.Name}}</td>
            <td class="UserIds" title="{{d[i].UserIds}}">{{d[i].UserIds}}</td>
        </tr>
        {{# } }}
    </script>

    <script type="text/html" id="tpl-msg-item">
        {{# for(var i = 0, len = d.length; i < len; i++){ }}
        <tr {{# if(i%2 == 0){ }} class="gradeX footable-even"
            {{# }else{ }} class="gradeX footable-odd" {{# } }}>
            <td class="Id" style="display: none;">{{d[i].Id}}</td>
            <td><input type="radio"  name="msg"  class="checkPlan" data-index="{{i}}" /></td>
            <td class="Name">{{d[i].Name}}</td>
            <td class="TemplateCode">{{d[i].TemplateCode}}</td>
        </tr>
        {{# } }}
    </script>
    <script>

        $(document).ready(function () {
            //layer.msg('玩命加载中……', { icon: 16, shade: 0.01, time: 0, maxWidth: 200 });

            var bindWxCorpInfoList = function (controller, action, params, els, size, callback) {
                Y.API2(controller, action, params, function (data) {
                    if (data.Success == false) {
                        swal(data.Message, '', 'error');
                    } else {
                        var html = '';
                        data.map(function (item) {
                            html += '<option value=' + item.CIdentification + '>' + (item.CorpName + '-' + item.AgentName) + '</option>';
                        });
                        els.map(function (item) {
                            $(item).html("");
                            $(item).html(html);
                            $(item).selectpicker({
                                size: size,
                                'title': '请选择'
                            });
                            $(item).selectpicker('refresh');
                        });
                        if (typeof callback === "function") {
                            callback();
                        }
                    }
                });
            }
            var loadWxCorpInfoList = function (els, callback) {
                bindWxCorpInfoList('WxCorpInfo', 'GetWxCorpInfoList', {}, els, 6, callback);
            }

            //模块ID
            var ModuleID = Y.getUrlParam("ModuleID");

            //获取按钮
            commonUtil.loadBtnList(ModuleID, function () {
                rScroll();
            });

            //自动高 DOCUMENT高减按钮栏+其它
            //$(".chooseArea .leftArea1").height($(document).height() - (35 + 145));

            $.expr[':'].textEquals = $.expr.createPseudo(function (arg) {
                return function (elem) {
                    return $(elem).text().match("^" + arg + "$");
                };
            });

            var to = false;
            $('.filter-users').on("keyup",function () {
                var v = $(".filter-users").val();
                if (to) { clearTimeout(to); }
                to = setTimeout(function () {
                    $('#UserList').jstree("search", v);
                }, 250);
            });

            var loadDepartmentList = function (wxWorkId) {
                Y.API2('WxUser', 'GetDepartmentList', { wxConfig: wxWorkId}, function (json) {
                    if (json.Success === false) {
                        swal(json.Message, '', 'error');
                    } else {
                        var newdata = $.map(json,
                            function (obj) {
                                obj.parent = obj.parentid == "0" ? "#" : obj.parentid;
                                obj.state = { opened: (obj.parentid === 1) || obj.id === 1 };
                                obj.li_attr = { id: obj.id, userId: obj.UserId };
                                obj.type = (obj.UserId === "" ? "default" : "child");
                                obj.text = obj.name;
                                return obj;
                            });
                        console.log(newdata);

                        //数据组列表
                        $('#groupdata').jstree(
                            {
                                'core': { data: newdata },
                                "checkbox": { "keep_selected_style": false },
                                "types": {
                                    "default": { "icon": "fa fa-folder text-info" },
                                    "child": { "icon": "fa fa-user" }
                                },
                                "plugins": ["checkbox", "types"]
                            }).on("ready.jstree", function () {
                                console.log("ready.jstree");
                                layer.closeAll('dialog');
                            }).on("changed.jstree", function (e, data) {
                                //console.log(data.selected);
                                //layer.msg('玩命加载中……', { icon: 16, shade: 0.01, time: 0, maxWidth: 200 });
                                console.log(data.node.li_attr.id, data.node.li_attr.userId);
                                //debugger 
                            });
                    }
                    // console.log(data)
                });
            }


            //获取右边列表
            var loadReportList = function (wxWorkId) {
                $('#pageList').empty();
                $('#pageList').html('');
                var conditionTitle = $('.filter-users').val().trim().replace(/'/g, '');
                pageControl.init('WxReport', 'GetReportList', {
                    conditionTitle: conditionTitle,
                    wxConfig: wxWorkId,
                    needLayer: true,
                    alwaysCallBack: function () {
                        //$('#pageList').empty();
                    }
                }, function (result) {
                    var tBody = [];
                    if (!Y.checkNull(result)) {
                        if (result.data.length == 0) {
                            Y.NoData(body, 5);
                            return false;
                        }
                        var pl = document.getElementById('tpl-rpt-item').innerHTML;
                        laytpl(pl).render(result.data, function (html) {
                            document.getElementById('pageList').innerHTML = html;

                            $("#pageList .checkPlan").iCheck({
                                checkboxClass: "icheckbox_square-green",
                                radioClass: "iradio_square-green"
                            });

                            $('#pageList .checkPlan').on('ifChecked', function (event) {
                                $('#pageList tr').removeClass('check');
                                $(this).parents('tr').addClass('check');
                            });

                            $('#pageList .checkPlan').on('ifUnchecked', function (event) {
                                $('#pageList .footable tr').removeClass('check');
                            });
                        });
                        rScroll();
                    }
                });
            }


            //获取消息模板列表
            var loadMessageList = function () {
                $('#MessageList').empty();
                $('#MessageList').html('');
                pageControl.init('WxMsgTemplate', 'GetAutoSendMsgTemplateList', {
                    needLayer: true,
                    alwaysCallBack: function () {
                        //$('#MessageList').empty();
                    }
                }, function (result) {
                    var tBody = [];
                    if (!Y.checkNull(result)) {
                        if (result.data.length == 0) {
                            Y.NoData(tBody, 5);
                            return false;
                        }
                        var pl = document.getElementById('tpl-msg-item').innerHTML;
                        laytpl(pl).render(result.data, function (html) {
                            document.getElementById('MessageList').innerHTML = html;

                            //$(".footable").icheckAll({
                            //    checkObj: ".checkPlan", //表格下面的选择控件对象 选择器
                            //    checkAllObj: "#checkAllPlan", //全选 选择器
                            //    clickoutBoxCheck: false, //点击行 不选中
                            //    checkboxMargin: "4px 0 0 0 " //上右下左
                            //});

                            $("#MessageList .checkPlan").iCheck({
                                checkboxClass: "icheckbox_square-green",
                                radioClass: "iradio_square-green"
                            });

                            $('#MessageList .checkPlan').on('ifChecked', function (event) {
                                $('#MessageList tr').removeClass('check');
                                $(this).parents('tr').addClass('check');
                            });
                        });
                        rScroll();
                    }
                });
            }
            loadMessageList();

            //过虑 筛选用户
            $(".btn-filter-users").on("click", function () {
                loadReportList();
            });


            //选中记录
            $('#pageList').on('click', 'tr', function () {
                var parentObj = "#pageList";
                if ($(this).hasClass('check')) {
                    $(parentObj +' tr').removeClass('check');
                    $(parentObj +' tr .checkPlan').iCheck('uncheck');
                } else {
                    $(parentObj +' tr').removeClass('check');
                    $(this).addClass('check');

                    $(parentObj +' tr .checkPlan').iCheck('uncheck');
                    $(this).find('.checkPlan').iCheck('check');
                }
            });


            //选中记录
            $('#MessageList').on('click', 'tr', function () {
                $('#MessageList tr').removeClass('check');
                $(this).addClass('check');

                $('#MessageList tr .checkPlan').iCheck('uncheck');
                $(this).find('.checkPlan').iCheck('check');
            });

            var selectMessageList = function(tr) {
                if (tr === null) {
                    return;
                }

                $('#MessageList tr').removeClass('check');
                $('#MessageList tr .checkPlan').iCheck('uncheck');

                $(tr).addClass('check');
                $(tr).find('.checkPlan').iCheck('check');
            };


            var selectReportList = function (tr) {
                if (tr === null) {
                    return;
                }
                var parentObj = "#pageList";
                $(parentObj + ' tr').removeClass('check');
                $(parentObj + ' tr .checkPlan').iCheck('uncheck');

                $(tr).addClass('check');
                $(tr).find('.checkPlan').iCheck('check');
            };


            //选中记录
            $('#SettingList').on('click', 'tr', function () {

                var tree = $('#groupdata').jstree(true);
                if (tree === false) {
                    swal("请选择要操作的企业微信", '', 'error');
                    return false;
                }

                if ($(this).hasClass('check')) {
                    $('#SettingList tr').removeClass('check');
                    $('#SettingList tr .checkPlan').iCheck('uncheck');
                } else {
                    $('#SettingList tr').removeClass('check');
                    $(this).addClass('check');

                    $('#SettingList tr .checkPlan').iCheck('uncheck');
                    $(this).find('.checkPlan').iCheck('check');



                    var id = $(this).find('.Id').text();
                    Y.API2('WxAutoSendSetting', "GetWxAutoSendSetting", { Id: id }, function (data) {
                        if (data.Success == false) {
                            console.log(data.Message);
                        } else {
                            console.log(data);
                            var tr = $('#MessageList td:textEquals(' + data.TemplateId + ')').parents('tr');
                            selectMessageList(tr);

                            tree.deselect_all(true);
                            var uidArr = data.UserIds.split("|");
                            for (var i = 0; i < uidArr.length; i++) {
                                var uid = uidArr[i];
                                var treeId = $('#groupdata li[userid="' + uid + '"]').attr('id');
                                tree.check_node(treeId);
                                console.log(treeId);
                            }

                            var rptTr = $('#pageList td:textEquals(' + data.ReportId + ')').parents('tr');
                            selectReportList(rptTr);
                        }
                    });
                }
            });


            $('#wxWorkSelectList').on('changed.bs.select', function (e) {
                var wxWorkId = $('#wxWorkSelectList').selectpicker('val');
                console.log(wxWorkId);
                //layer.msg('玩命加载中……', { icon: 16, shade: 0.01, time: 0, maxWidth: 200 });
                $('#groupdata').jstree("destroy");

                loadDepartmentList(wxWorkId);
                loadReportList(wxWorkId);
            });

            loadWxCorpInfoList(["#wxWorkSelectList"]);



            //获取消息模板列表
            var loadSettingList = function () {
                $('#SettingList').empty();
                $('#SettingList').html('');
                pageControl.init('WxAutoSendSetting', 'GetWxAutoSendSettingList', {
                    needLayer: true,
                    alwaysCallBack: function () {
                        //$('#SettingList').empty();
                    }
                }, function (result) {
                    var tBody = [];
                    if (!Y.checkNull(result)) {
                        if (result.data.length == 0) {
                            Y.NoData(body, 5);
                            return false;
                        }
                        var pl = document.getElementById('tpl-setting-item').innerHTML;
                        laytpl(pl).render(result.data, function (html) {
                            document.getElementById('SettingList').innerHTML = html;

                            $("#SettingList .checkPlan").iCheck({
                                checkboxClass: "icheckbox_square-green",
                                radioClass: "iradio_square-green"
                            });

                            $('#SettingList .checkPlan').on('ifChecked', function (event) {
                                $('#SettingList tr').removeClass('check');
                                $(this).parents('tr').addClass('check');
                            });
                        });
                        rScroll();
                    }
                });
            }
            loadSettingList();


            //提交
            $(document).on("click", "#btn-save", function () {

                var tid = 0;
                $('#MessageList .checkPlan:checked').parents('tr').each(function (index, element) {
                    var id = $(element).find('.Id').text();
                    tid = id;
                });

                if (tid === 0) {
                    swal("请选择要删除的消息模板", '', 'error');
                    return false;
                }


                var userIdList = [];
                var tree = $('#groupdata').jstree(true);
                if (tree === false) {
                    swal("请选择要操作的企业微信", '', 'error');
                    return false;
                }
                var selectedNodeIdArr = tree.get_bottom_selected();
                for (var i = 0; i < selectedNodeIdArr.length; i++) {
                    var id = selectedNodeIdArr[i];
                    var node = tree.get_node(id);
                    var userId = node.li_attr.userId || "";
                    if (userId !== "") {
                        userIdList.push(userId);
                    }
                }

                if (userIdList.length === 0) {
                    swal("请选择要操作的用户", '', 'error');
                    return false;
                }

                var reportId = 0;
                $('#pageList .checkPlan:checked').parents('tr').each(function (index, element) {
                    var id = $(element).find('.Id').text();
                    reportId = id;
                });

                var wxWorkId = $('#wxWorkSelectList').selectpicker('val');
                console.log(userIdList, tid, reportId);


                var tr = $('#SettingList .checkPlan:checked').parents('tr');
                var setId = $(tr).find('.Id').text() || 0;


                Y.API2('WxMsgTemplate', 'SetAutoSendMsgSetting',
                    {
                        Id: setId,
                        WxConfig: wxWorkId,
                        MemberIdList: userIdList,
                        MsgTemplateId: tid,
                        ReportId: reportId
                    }, function (data) {
                        if (data.Success == false) {
                            swal(data.Message, '', 'error');
                        } else {
                            swal("保存成功", '', 'success');
                            $('.filter-users').val("");
                            loadSettingList();
                        }
                    });
            });


            $(document).on("click", "#deleteBtn", function () {

                var tr = $('#SettingList .checkPlan:checked').parents('tr');
                var setId = $(tr).find('.Id').text() || 0;


                if (setId === 0) {
                    swal("请选择要删除的消息模板", '', 'error');
                    return false;
                }

                swal({
                    title: "您确定要删除这条记录吗",
                    text: "删除后将无法恢复，请谨慎操作！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "删除",
                    cancelButtonText: "取消",
                    closeOnConfirm: false
                }, function () {
                    Y.API2('WxAutoSendSetting', "RemoveWxAutoSendSetting", { Id: setId }, function (data) {
                        if (data.Success == false) {
                            swal(data.Message, '', 'error');
                        } else {
                            swal("删除成功", '', 'success');
                            loadSettingList();
                        }
                    });
                });
            });
        })
    </script>
</asp:Content>

